package com.yiren.backstage.communication.api;

import android.content.Context;
import android.os.Looper;

import com.yiren.backstage.communication.interfaces.DataCallback;
import com.yiren.backstage.communication.services.AbstractPortService;
import com.yiren.backstage.communication.thread.ReadDataThread;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;

/**
 * Time:2021/12/23 14:45
 * Author:xiaozan
 * Description:设备通讯接口 父类
 */
public abstract class AbstractCommunication implements ICommunication {

    private Context context;
    protected int deviceType;
    protected DataCallback dataCallback;

    protected AbstractPortService abstractPortService;

    public AbstractCommunication(Context context, int deviceType) {
        this.context = context;
        this.deviceType = deviceType;
    }

    /**
     * @param dataCallback dataCallback 回调接口
     */
    public void setDataCallback(DataCallback dataCallback) {
        this.dataCallback = dataCallback;
        abstractPortService.setDataCallback(dataCallback);
    }

    @Override
    public void start() {
        if (dataCallback != null) dataCallback.onStateChange(0, "正在连接...");
        new Thread(() -> {
            try {
                if (abstractPortService.start()) {
                    Looper.prepare();
                    new ReadDataThread(context, abstractPortService).start();
                    if (dataCallback != null) dataCallback.onStateChange(0, "解析中");
                    Looper.loop();
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (dataCallback != null)
                    dataCallback.onStateChange(0, "设备连接异常：" + e.getMessage());
            }
        }).start();
    }

    @Override
    public void stop() {
        if (dataCallback != null) dataCallback.onStateChange(0, "正在断开设备连接...");
        new Thread(() -> {
            try {
                abstractPortService.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (dataCallback != null) dataCallback.onStateChange(0, "设备连接已断开");
        }).start();
    }

    @Override
    public synchronized void writeData(byte[] data, String replyHead, DataCallback sendDataCallback) {
        try {
            abstractPortService.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(replyHead)) return;
        new Thread(() -> {
            long sendTime = System.currentTimeMillis();
            int sendCount = 0;
            while (true) {
                String readData = dataCallback.getReadData();
                if (null != readData && readData.contains(replyHead)) {
                    sendDataCallback.onSendReadData(readData);
                    return;
                } else {
                    //发送三次后未接收到数据 返回null
                    if (sendCount > 3) {
                        sendDataCallback.onSendReadData(null);
                        return;
                    }
                    if ((System.currentTimeMillis() - sendTime) / 500 > 1) {
                        try {
                            abstractPortService.write(data);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        sendTime = System.currentTimeMillis();
                        sendCount++;
                    }
                }
            }
        }).start();
    }
}
